#! /usr/bin/python3 python3
# -*- coding: utf-8 -*-

# *************************************************************
#  Projectname @  pysm
#     Filename @  pydb.py
#       Author @  Steve.ma
#  Create date @  2018/8/31
#  Description @  
# *************************************************************

import pymysql
from Conf import getConf

con = None
cursor = None

class SMSql:
    conf = None
    cursor = False
    con = False
    transaction = False
    effect_row = 0

    def __init__(self):
        conf = getConf("mysql")
        # self.log("Mysql配置：")
        # self.log(conf)
        self.conf = conf
        return

    def __del__(self):
        self.close_conn()
        return
    #连接
    def conn(self):
        global con
        global cursor

        conf = self.conf
        if self.con != False :
            return
        else :
            try:
                if con != None :
                    self.con = con
                else :
                    self.con = pymysql.connect(
                        host=conf['host'],
                        port=conf['port'],
                        user=conf['user'],
                        password=conf['passwd'],
                        charset=conf['charset'],
                        database=conf['database']
                    )
                if cursor != None :
                    self.cursor = cursor
                else :
                    self.cursor = self.con.cursor()
            except pymysql.Error as e:
                print(e)
        return

    #关闭连接
    def close_conn(self):
        #获取cursor
        if self.cursor == False or self.con == False :
            self.conn()
        try:
            if self.con:
                self.con.close()
                self.con = False
            if self.cursor :
                self.cursor.close()
                self.cursor = False
        except pymysql.Error as e:
            print(e)
        return

    #获取数据库中的一条数据
    def queryOne(self, sql, args = None):
        #获取cursor
        if self.cursor == False or self.con == False :
            self.conn()
        # 执行sql
        effect_row = self.cursor.execute(sql, args)
        # 拿到结果   dict(zip(['a','b'],(1,2)))  ==> {'a': 1, 'b': 2}  cursor.fetchone 拿到的是这条数据的元祖格式
        res = dict(zip([x[0] for x in self.cursor.description], self.cursor.fetchone()))
        if self.transaction == False :
            # 关闭cursor/连接
            self.close_conn()
        #返回结果
        return res
    #获取数据库中的多条数据
    def queryAll(self, sql, args = None):
        #获取cursor
        if self.cursor == False or self.con == False :
            self.conn()
        # 执行sql
        effect_row = self.cursor.execute(sql, args)
        # 拿到结果
        # print(cursor.fetchall())
        res = [dict(zip([x[0] for x in self.cursor.description], row)) for row in self.cursor.fetchall()]
        if self.transaction == False :
            # 关闭cursor/连接
            self.close_conn()
        # 返回结果
        return res
    #执行sql
    def query(self, sql, args = None):
        #获取cursor
        if self.cursor == False or self.con == False :
            self.conn()
        try:
            # 执行SQL语句
            self.effect_row = self.cursor.execute(sql, args)
            # 获取自增id
            return True
        except:
            # 发生错误时
            return False
    #插入记录
    def queryAdd(self, sql, args = None):
        #获取cursor
        if self.cursor == False or self.con == False :
            self.conn()
        try:
            # 执行SQL语句
            self.effect_row = self.cursor.execute(sql, args)
            # 获取自增id
            return self.cursor.lastrowid
        except:
            # 发生错误时
            return False
    def begin(self):
        #获取cursor
        if self.cursor == False or self.con == False :
            self.conn()
        self.transaction = True
        return
    def commit(self):
        self.con.commit()
        self.transaction = False
        return
    def rollback(self):
        self.con.rollback()
        self.transaction = False
        return
